import os
import json
from openai import OpenAI
from config import DOUPOU_MODEL_CONFIG
def save_history(history, file_path):
    with open(file_path, 'w', encoding='utf-8') as f:
        json.dump(history, f, ensure_ascii=False)

def load_history(file_path):
    if os.path.exists(file_path):
        with open(file_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    return []

def main(q, history_file_path='history.json'):
    client = OpenAI(
        api_key = DOUPOU_MODEL_CONFIG['API_KEY'],
        base_url = DOUPOU_MODEL_CONFIG['BASE_URL'],
    )

    # 加载历史
    history = load_history(history_file_path)

    # 将之前的对话历史和当前的输入合并
    messages = history + [
        {"role": "system", "content": DOUPOU_MODEL_CONFIG['SYSTEM']},
        {"role": "user", "content": "{}".format(q)}
    ]

    # Non-streaming:
    # print("----- standard request -----")
    completion = client.chat.completions.create(
        model = DOUPOU_MODEL_CONFIG['MODEL'],  # your model endpoint IDp
        messages = messages,
    )

    # 更新对话历史
    history.append({"role": "user", "content": q})
    history.append({"role": "assistant", "content": completion.choices[0].message.content})

    # 保存历史
    save_history(history, history_file_path)

    return completion.choices[0].message.content


if __name__ == '__main__':
    print(main('写一首诗'))